Styling Form Fields Using :focus and :valid in CSS
You can use the :focus and :valid pseudo-classes together to style form fields based on their state. The :focus pseudo-class applies styles when a field is active (clicked or selected), while :valid applies when the field’s input satisfies its validation rules.
:focus targets form fields that are currently active or being edited by the user.
:valid targets fields whose values meet validation criteria, such as matching a pattern or not being empty when required.
You can combine them as input:focus:valid to apply styles only when both conditions are true.
In this example, when the user clicks the input field, it gets a blue border due to :focus. Once a valid email is entered, the border turns green. When both focused and valid, the input background changes to light green.
Use :focus and :valid to give users clear visual feedback on form interactions.
Combine pseudo-classes like :focus:invalid for error highlighting.
Ensure validation rules (like type or pattern) are properly set in HTML.
Maintain accessibility by ensuring color changes have sufficient contrast.